#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>//引入头文件
extern errno;//引入变量

#define BUFFSIZE 4096

int main(int argc, char *argv[]){
    int f_source, f_dest;
    char  buf[BUFFSIZE];
    int f_source_length;
    int m,n;
    if( (f_source=open(argv[1],O_RDONLY))==-1){
        perror(argv[1]);
        exit(-1);
    }
        
    
    struct stat st;
    stat(argv[2],&st);
    if (S_ISDIR(st.st_mode)){
        //printf("is a dir\n");
        char fn[30],*p;
    
          //上句假设以某种方式获得的全文件名在pathname中,"..."中只是举例
        strcpy(fn,(p=strrchr(argv[1],'/')) ? p+1 : argv[1]);
          //上句函数第2实参这样写以防止文件在当前目录下时因p=NULL而出错
        char *dest = argv[2];
        strcat(dest, "/");
        strcat(dest, fn);
        //printf(dest); 
        if ((f_dest=open(dest,O_WRONLY|O_CREAT|O_TRUNC))==-1)
		    perror(argv[2]);
    }else{
        if ((f_dest=open(argv[2],O_WRONLY|O_CREAT|O_TRUNC))==-1)
		    perror(argv[2]);
        //printf("through else");
    }
        	
	while ((n=read(f_source, buf, BUFFSIZE))>0)
	{
		//printf("buf:%d", strlen(buf));
		if (n!=(m=write(f_dest, buf, n))){
			printf("write error");
			exit(-1);
        }
	}
    

    close(f_source);
	close(f_dest);
	//free(buf);

	return 0;

}   
